package com.yunc.modules.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrSpliter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunc.base.interceptor.annotation.RepeatSubmit;
import com.yunc.base.utils.R;
import com.yunc.base.utils.SecurityUtils;
import com.yunc.modules.sys.entity.SysNotice;
import com.yunc.modules.sys.service.ISysNoticeService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 通知公告
 *
 * @author congcong tao
 * @create 2018/12/16 6:34 PM
 */
@RestController
@RequestMapping("sysNotice")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SysNoticeController {

    private final ISysNoticeService sysNoticeService;

    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermi('sys:notice:list')")
    public R page(Page<SysNotice> page, SysNotice sysNotice) {
        List<SysNotice> sysNoticeList = sysNoticeService.pageInfo(page, sysNotice);
        return R.ok().put("data", sysNoticeList).put("count", page.getTotal());
    }

    @GetMapping("/info/{id}")
    public R info(@PathVariable String id) {
        SysNotice notice = sysNoticeService.getById(id);
        return R.ok().put("sysNotice", notice);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('sys:notice:save')")
    public R save(SysNotice notice) {
        // 创建者
        notice.setCreator(SecurityUtils.getUserId());
        notice.setCreateTime(new Date());
        boolean flag = sysNoticeService.save(notice);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @RepeatSubmit
    @PutMapping(value = "/update")
    @PreAuthorize("@ss.hasPermi('sys:notice:update')")
    public R update(SysNotice notice) {
        boolean flag = sysNoticeService.updateById(notice);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     * hasRole保存的是主键
     */
    @DeleteMapping("/delete/{ids}")
    @PreAuthorize("@ss.hasPermi('sys:notice:delete') AND @ss.hasRole('1')")
    public R delete(@PathVariable String ids) {
        List<String> idsList = StrSpliter.splitTrim(ids, ',', true);
        if (CollUtil.isEmpty(idsList)) {
            return R.error("传入值格式错误");
        }
        boolean flag = sysNoticeService.removeByIds(idsList);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }
}
